<?php

namespace backend\modules\member\forms;

use Yii;
use yii\base\Model;
use yii\web\NotFoundHttpException;
use common\models\member\Member;
use common\helpers\TreeHelper;

/**
 * 变更推荐人
 */
class MoveTjForm extends Model
{
    public $username;
    public $toUsername;

    public function rules()
    {
        return [
            [['username', 'toUsername'], 'required'],
            [
                ['username'],
                'exist',
                'targetClass' => Member::class,
                'targetAttribute' => 'username',
            ],
            [
                ['toUsername'],
                'exist',
                'targetClass' => Member::class,
                'targetAttribute' => 'username',
            ],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => '变更会员',
            'toUsername' => '新推荐人',
        ];
    }

    public function move()
    {
        // 写入当前会员
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $member = Member::findOne(['username'=>$this->username]);
            if (!$member) {
                throw new \Exception('会员不存在', 1);
            }
            $toMember = Member::findOne(['username'=>$this->toUsername]);
            if (!$member) {
                throw new \Exception('新推荐人不存在', 1);
            }
            if ($member->pid == $toMember->id || $member->id == $toMember->id) {
                throw new \Exception('没有变更', 1);
            }
            // 新接点人不能在会员自己下面
            $treeStr = $toMember->tree;
            $treeStr = str_replace(TreeHelper::PREFIX, '', $treeStr);
            $ids = explode(TreeHelper::SEPARATOR, $treeStr);
            if (in_array($member->id, $ids)) {
                throw new \Exception('不能转到会员自己团队下', 1);
            }
            $update = Member::updateAllCounters(['promo_amount'=>-1], ['id'=>$member->pid]);
            if (!$update) {
                throw new \Exception('减少推荐人数失败', 1);
            }
            $update = Member::updateAllCounters(['promo_amount'=>1], ['id'=>$toMember->id]);
            if (!$update) {
                throw new \Exception('添加推荐人数失败', 1);
            }
            $member->pid = $toMember->id;
            if (!$member->save()) {
                throw new \Exception('修改失败', 1);
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->addError('username', $e->getMessage());
            return false;
        }

        return true;
    }
}